package com.it.tydic.estate.module.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.cache.DictionaryCache;
import com.it.tydic.estate.common.util.*;

import com.it.tydic.estate.module.mapper.inner.FangjianguanliMapper;
import com.it.tydic.estate.module.mapper.inner.GuanlichuMapper;
import com.it.tydic.estate.module.mapper.inner.LouyuMapper;
import com.it.tydic.estate.module.model.inner.Fangjianguanli;
import com.it.tydic.estate.module.model.inner.Guanlichu;
import com.it.tydic.estate.module.model.inner.Louyu;
import com.it.tydic.estate.module.service.FJglService;
import com.it.tydic.estate.module.service.XqglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.text.NumberFormat;
import java.util.*;

/**
 * 房间管理实现
 */
@Service
@Transactional
public class FJglServiceImpl implements FJglService {
    @Autowired
    private FangjianguanliMapper fangjianguanliMapper;
    @Resource
    private GuanlichuMapper guanlichuMapper;//小区
    @Autowired
    private LouyuMapper louyuMapper;//楼宇

    /**
     * 房间添加或修改
     *
     * @param fangjianguanli
     * @return
     */
    @Override
    public Result addOrUpload(Fangjianguanli fangjianguanli) {
        if(StringUtil.isEmpty(fangjianguanli.getFjbh())||StringUtil.isEmpty(fangjianguanli.getFjcqr())
                || StringUtil.isEmpty(fangjianguanli.getXqid()) || StringUtil.isEmpty(fangjianguanli.getLyid())){//参数非空验证
            return  Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        String userId= CurrentUtil.getCurrentUserId();
        if (fangjianguanli.getId() == null || "".equals(fangjianguanli.getId())) {//判断是否有主键
            long id = new InstaIdGenerator().nextId(TimeUtil.timeGen());//生成Id主键
            fangjianguanli.setId(String.valueOf(id));
            fangjianguanli.setCjsj(new Date());
            fangjianguanli.setXgsj(new Date());
            fangjianguanli.setZfbj(ZfbjFinalUtil.zfbj_zy);
            fangjianguanli.setCuserId(userId);
            int result = fangjianguanliMapper.insertSelective(fangjianguanli);
            if (result < 0)
                return Result.error(CodeMsg.INTER_ERROR);
        } else {
            fangjianguanli.setXgsj(new Date());
            fangjianguanli.setUuserId(userId);
            int result = fangjianguanliMapper.updateByPrimaryKeySelective(fangjianguanli);
            if (result < 0){
                return Result.error(CodeMsg.UPDATE_ERROR);
            }
        }
        return Result.success(fangjianguanli.getId());
    }

    /**
     * 条件分页查房间信息
     *
     * @param fjglMap
     * @return
     */
    @Override
    public Result queryList(Map<String, Object> fjglMap) {
        Map<String, Object> map = new HashMap<>();
        if (fjglMap.containsKey("pageNum") && fjglMap.containsKey("pageSize")) {//判断是否有分页条件有进行分页
            PageHelper.startPage((Integer) fjglMap.get("pageNum"), (Integer) fjglMap.get("pageSize"));
        }
        Page<Fangjianguanli> xiaoquguanlis = fangjianguanliMapper.selectList(fjglMap);
        List<Fangjianguanli> result = xiaoquguanlis.getResult();
        if (result.size() > 0) {
            Map<String, String> villages = villageMap();//小区信息
            Map<String, String> builings = builingMap();
            for (Fangjianguanli fangjianguanli : result) {
                if (villages.containsKey(fangjianguanli.getXqid())) {//获取小区名称
                    fangjianguanli.setXqmc(villages.get(fangjianguanli.getXqid()));
                } else {
                    fangjianguanli.setXqmc("");
                }
                if (builings.containsKey(fangjianguanli.getLyid())) {//获取楼宇名称
                    fangjianguanli.setLymc(builings.get(fangjianguanli.getLyid()));
                } else {
                    fangjianguanli.setLymc("");
                }
                fangjianguanli.setSffwdx(DictionaryCache.getDicVal(fangjianguanli.getSffwdx()));//收费服务对象
                fangjianguanli.setFjlx(DictionaryCache.getDicVal(fangjianguanli.getFjlx()));//房间类型
                fangjianguanli.setFjzt(DictionaryCache.getDicVal(fangjianguanli.getFjzt()));//房间状态
                fangjianguanli.setZxqk(DictionaryCache.getDicVal(fangjianguanli.getZxqk()));//装修情况
            }
        }
        map.put("result", result);
        map.put("totle", xiaoquguanlis.getTotal());
        return Result.success(map);
    }

    /**
     * 根据主键删除房间
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(String id) {
        if (!StringUtils.isNotEmpty(id))//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Fangjianguanli fangjianguanli = new Fangjianguanli();
        fangjianguanli.setId(id);
        fangjianguanli.setZfbj(ZfbjFinalUtil.zfbj_zf);
        int result = fangjianguanliMapper.updateByPrimaryKeySelective(fangjianguanli);
        if (result <= 0)
            return Result.error(CodeMsg.DELETE_ERROR);
        return Result.success();
    }

    /**
     * 批量删除
     *
     * @param list 主键集合
     * @return
     */
    @Override
    public Result deleteBatch(List<String> list) {
        if (list == null || list.size() <= 0)//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Example example = new Example(Fangjianguanli.class);
        example.createCriteria().andIn("id", list);
        Fangjianguanli fangjianguanli = new Fangjianguanli();
        fangjianguanli.setZfbj(ZfbjFinalUtil.zfbj_zf);
        int result = fangjianguanliMapper.updateByExampleSelective(fangjianguanli, example);
        if (result <= 0)
            return Result.error(CodeMsg.DELETE_ERROR);
        return Result.success();
    }


    /**
     * 根据小区或楼宇主键删除房间信息
     *
     * @param type 0:楼宇Id ，1:小区id
     * @param list 小区主键集合
     * @return
     */
    @Override
    public Result deleteBatchByXqid(String type, List<String> list) {
        if (list == null || list.size() <= 0)//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        String field = "xqid";
        if ("0".equals(type)) {//根据type类型更改id
            field = "lyid";
        }
        Example example = new Example(Fangjianguanli.class);
        example.createCriteria().andIn(field, list);
        Fangjianguanli fangjianguanli = new Fangjianguanli();
        fangjianguanli.setZfbj(ZfbjFinalUtil.zfbj_zf);
        int result = fangjianguanliMapper.updateByExampleSelective(fangjianguanli, example);
        return Result.success();
    }

    /**
     * 根据主键查询房间
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(String id) {
        if (!StringUtils.isNotEmpty(id))//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Fangjianguanli fangjianguanli = fangjianguanliMapper.selectByPrimaryKey(id);
        if(fangjianguanli==null){
            return Result.error(CodeMsg.DATA_NOT_EXIST);
        }
        return Result.success(fangjianguanli);
    }

    /**
     * 根据楼宇主键查楼宇房间
     *
     * @param id 楼宇主键
     * @return
     */
    @Override
    public Result queryByLyId(String id) {
        if (!StringUtils.isNotEmpty(id))//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Example example = new Example(Fangjianguanli.class);
        example.createCriteria().andEqualTo("lyid", id).andEqualTo("zfbj", ZfbjFinalUtil.zfbj_zy);
        List<Fangjianguanli> fangjianguanlis = fangjianguanliMapper.selectByExample(example);
        return Result.success(fangjianguanlis);
    }

    /**
     * 获取顺序号
     *
     * @param id 小区主键
     * @return
     */
    @Override
    public Result getOrderByNum(String id) {
        if (!StringUtils.isNotEmpty(id))//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Long fjsxh = fangjianguanliMapper.getOrderByNum(id);
        if (fjsxh <= 10000) {
            fjsxh = 10001L;
        } else {
            fjsxh = fjsxh + 1;

        }
        return Result.success(fjsxh);
    }

    /**
     * 获取每个小区房间数和方间类型统计
     *
     * @return
     */
    @Override
    public Result getbuildingTypeCont(Map<String,Object> map) {

        List<Map<String, Object>> list = new LinkedList<>();
        List<Map<String, Object>> childen = null;
        List<Map<String, Object>> fangjianguanlis = fangjianguanliMapper.selectCountbyXqid(map);//每个小区房间数量统计
        List<Map<String, Object>> fangjianguanliList = fangjianguanliMapper.selectCountByFjlx(map);//统计不同小区不同类型房间数
        if (fangjianguanlis.size() > 0) {
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            int id =1;//定义唯一标识
            for (Map<String, Object> village : fangjianguanlis) {
                village.put("xqlx", "合计:");
                village.put("xqlxbfb","100%");
                village.put("jzmjbfb","100%");
                childen = new LinkedList<>();
                village.put("id",id++);
                for (Map<String, Object> builing : fangjianguanliList) {
                    if (village.get("xqid").equals(builing.get("xqid"))) {
                        builing.put("id",id++);
                        builing.put("xqlx", DictionaryCache.getDicVal(builing.get("fjlx") + ""));
                        builing.put("xqlxbfb",numberFormat.format((Float.parseFloat(builing.get("num")+"") /Float.parseFloat(village.get("num")+"")* 100))+"%");
                        if(Float.parseFloat( village.get("jzmj")+"")>0){
                            builing.put("jzmjbfb", numberFormat.format((Float.parseFloat( builing.get("jzmj")+"") /Float.parseFloat( village.get("jzmj")+"") * 100))+"%");
                        }else {//当总面积为0时百分比设为空
                            village.put("jzmjbfb","");
                            builing.put("jzmjbfb","");
                        }
                        childen.add(builing);
                    }
                }
                village.put("children", childen);
            }
        }
        return Result.success(fangjianguanlis);
    }

    /***
     * 根据楼宇主键查询房间并案楼层展示
     * @return
     */
    @Override
    public Result queryVillageByLc(String id) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Fangjianguanli> fjlclist =   fangjianguanliMapper.selectLcList(id);//获取楼层按从低到高排序
        Example example = new Example(Fangjianguanli.class);
        example.createCriteria().andEqualTo("lyid", id).andEqualTo("zfbj", ZfbjFinalUtil.zfbj_zy);
        example.orderBy("lcs");
        List<Fangjianguanli> fangjianguanlis = fangjianguanliMapper.selectByExample(example);//查询楼宇房间
        List<Fangjianguanli> fangjianguanlilist=null;
        if(fjlclist.size()>0){
            Map<String, Object> map = null;
            for (Fangjianguanli fjlcs :fjlclist) {
                map = new HashMap<>();
                map.put("lcs",fjlcs.getLcs());
                fangjianguanlilist=new ArrayList<>();
                for (Fangjianguanli fangjianguanli:fangjianguanlis) {//获取同一楼层房间
                  if(fjlcs.getLcs()==fangjianguanli.getLcs()){
                      fangjianguanlilist.add(fangjianguanli);
                      fangjianguanli.setFjzt(DictionaryCache.getDicVal(fangjianguanli.getFjzt()));//房间状态
                  }
                }
                map.put("fangjianguanlis",fangjianguanlilist);
                list.add(map);
            }
        }
        return Result.success(list);
    }

    /**
     * 获取小区信息存入map中
     *
     * @return
     */
    public Map<String, String> villageMap() {
        Map<String, String> map = new HashMap<>();
        Example example = new Example(Guanlichu.class);
        example.createCriteria().andEqualTo("zfbj", ZfbjFinalUtil.zfbj_zy);
        List<Guanlichu> guanlichus = guanlichuMapper.selectByExample(example);
        if (guanlichus.size() > 0) {//将查询出的小区信息封装map中
            for (Guanlichu guanlichu : guanlichus) {
                if (!map.containsKey(guanlichu.getId())) {
                    map.put(guanlichu.getId(), guanlichu.getName());
                }
            }
        }
        return map;
    }

    /**
     * 获取楼宇信息存入map中
     *
     * @return
     */
    public Map<String, String> builingMap() {
        Map<String, String> map = new HashMap<>();
        Example example = new Example(Louyu.class);
       // example.createCriteria().andEqualTo("zfbj", ZfbjFinalUtil.zfbj_zy);
        List<Louyu> louyus = louyuMapper.selectByExample(example);
        if (louyus.size() > 0) {//将查询出的楼宇信息封装map中
            for (Louyu louyu : louyus) {
                if (!map.containsKey(louyu.getId())) {
                    map.put(louyu.getId(), louyu.getLymc());
                }
            }
        }
        return map;
    }

    /**
     * 房间示图租赁状况统计
     * @param lyid
     * @return
     */
    private Map<String,Object> leasingStatusCount(String lyid){
     return    fangjianguanliMapper.leasingStatusCount(lyid);
    }
}
